#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "comm.hpp"

int main()
{
    umask(0);
    // 新建命名管道
    int n = mkfifo(FIFO_FILE, 0666);
    if(n != 0)
    {
        std::cerr << "mkdir fifo error" << std::endl;
        return 1;
    }
    std::cout << "kmfifo success" << std::endl;

    // 打开管道文件
    // write 方没有执行open的时候，read方，就要在open内部进行“阻塞”，直到有人把管道文件打开了，open才会返回
    int fd = open(FIFO_FILE, O_RDONLY);
    if(fd < 0)
    {
        std::cerr << "open fifo error" << std::endl;
        return 2;
    }
    std::cout << "open fifo success" << std::endl;

    // read
    while(true)
    {
        char buffer[1024];
        int number = read(fd, buffer, sizeof(buffer)-1);
        if(number > 0)
        {
            buffer[number] = 0;
            std::cout << "Client Says:\"" << buffer << "\"" << std::endl;
        }
        else if(number == 0)
        {
            // TODO
            std::cout << "client quit! me too!" << std::endl;
            break;
        }
        else
        {
            std::cerr << "read error" << std::endl;
            break;
        }
    }

    close(fd);

    // 删除管道
    n = unlink(FIFO_FILE);
    if(n == 0)
    {
        std::cout << "remove fifo success" << std::endl;
    }
    else
    {
        std::cout << "remove fifo failed" << std::endl;
    }
    return 0;
}